package org.robotlegs.base
{
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.utils.getDefinitionByName;
	
	import org.robotlegs.core.IMediator;
	

public class MediatorBase implements IMediator
{

	protected static var UIComponentClass:Class;
	protected static const flexAvailable:Boolean = checkFlex();
	protected static function checkFlex():Boolean
	{
		try
		{
			UIComponentClass = getDefinitionByName('mx.core::UIComponent') as Class;
		}
		catch (error:Error)
		{
			// do nothing
		}
		return UIComponentClass != null;
	}
	


	protected var viewComponent:Object;

	protected var removed:Boolean;

	
	
	
	public function preRegister():void
	{
		removed = false;
		
		if (flexAvailable && (viewComponent is UIComponentClass) && !viewComponent['initialized'])
		{
			IEventDispatcher(viewComponent).addEventListener('creationComplete', onCreationComplete, false, 0, true);
		}
		else
		{
			onRegister();
		}
	}
	

	public function onRegister():void
	{
	}
	

	public function preRemove():void
	{
		removed = true;
		onRemove();
	}
	

	public function onRemove():void
	{
	}
	
	
	public function getViewComponent():Object{return viewComponent;}
	public function setViewComponent(viewComponent:Object):void{this.viewComponent = viewComponent;}

	
	protected function onCreationComplete(e:Event):void
	{
		IEventDispatcher(e.target).removeEventListener('creationComplete', onCreationComplete);
		
		if (!removed)
			onRegister();
	}

}
}
